from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
import sqlite3
from pydantic import BaseModel

app = FastAPI()


# 设置 CORS
# from fastapi.middleware.cors import CORSMiddleware
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )


# 初始化数据库链接
def get_db():
    db_conn = sqlite3.connect("./db/test.db")
    return db_conn


# 创建表
@app.lifespan("startup")
async def startup():
    with get_db() as db:
        cursor = db.cursor()
        cursor.execute(
            """
            CREATE TABLE IF NOT EXISTS events_table (
                id INTEGER PRIMARY KEY,
                isProcess BOOLEAN DEFAULT FALSE,
                cameraIp TEXT NOT NULL,
                eventType TEXT NOT NULL,
                eventTime DATETIME NOT NULL,
                eventImage TEXT NOT NULL,
                eventVideo TEXT NOT NULL,
                isCorrect BOOLEAN DEFAULT FALSE
            )
        """
        )
        db.commit()


class PostEvent(BaseModel):
    cameraIp: str
    cameraRtsp: str
    eventType: str
    eventTime: str
    eventImage: str
    eventVideo: str


@app.post(path="/events/", summary="算法服务器 POST 事件到数据库")
async def post_event(item: PostEvent):
    # p = Process(
    #     target=save_video,
    #     args=(item.cameraRtsp, item.eventVideo),
    # )
    # p.start()

    with get_db() as db:
        cursor = db.cursor()
        cursor.execute(
            "INSERT INTO events_table (cameraIp, eventType, eventTime, eventImage, eventVideo) VALUES (?, ?, ?, ?, ?)",
            (
                item.cameraIp,
                item.eventType,
                item.eventTime,
                item.eventImage,
                item.eventVideo,
            ),
        )
        db.commit()

        return {"id": cursor.lastrowid}


app.mount("/", StaticFiles(directory="./site", html=True))

if __name__ == "__main__":
    import uvicorn

    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
